package com.cecsmsserve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cecsmsserve.entity.User;
import com.cecsmsserve.mapper.UserMapper;
import com.cecsmsserve.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cecsmsserve.util.JWTUtil;
import com.cecsmsserve.util.result.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 王郝浠
 * @since 2024-04-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public CommonResult register(User user) {
        try {
            // 检查用户名是否已存在
            QueryWrapper<User> usernameWrapper = new QueryWrapper<>();
            usernameWrapper.eq("username", user.getUsername());
            if (baseMapper.selectCount(usernameWrapper) > 0) {
                return new CommonResult(104, "用户名已存在", null);
            }

            // 检查手机号是否已注册
            QueryWrapper<User> phoneWrapper = new QueryWrapper<>();
            phoneWrapper.eq("telephone", user.getTelephone());
            if (baseMapper.selectCount(phoneWrapper) > 0) {
                return new CommonResult(105, "该手机号已被注册", null);
            }

            // 设置初始审核状态
            user.setAudit_status(0);  // 待审核
            user.setAudit_remark(null);

            // 设置默认角色
            user.setRoleId(2);  // 默认为普通用户

            // 从身份证号提取出生日期并计算年龄
            if (user.getIdNum() != null && user.getIdNum().length() >= 14) {
                String birthdayStr = user.getIdNum().substring(6, 14);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                Date birthday = sdf.parse(birthdayStr);
                user.setBirthday(birthday);
                
                // 计算年龄
                Calendar cal = Calendar.getInstance();
                int currentYear = cal.get(Calendar.YEAR);
                cal.setTime(birthday);
                int birthYear = cal.get(Calendar.YEAR);
                int age = currentYear - birthYear;
                user.setAge(age);
            }

            // 保存用户信息
            if (baseMapper.insert(user) > 0) {
                return new CommonResult(200, "注册成功，请等待管理员审核", null);
            } else {
                return new CommonResult(500, "注册失败，请稍后重试", null);
            }
        } catch (Exception e) {
            return new CommonResult(500, "注册失败：" + e.getMessage(), null);
        }
    }

    //计算年龄
    private static int getAge(LocalDate today, User user) {
        int year= today.getYear();
        int month= today.getMonthValue();
        int day= today.getDayOfMonth();
        System.out.println(year+"年"+month+"月"+day+"号");
        
        Calendar birthCal = Calendar.getInstance();
        birthCal.setTime(user.getBirthday());
        int birthYear = birthCal.get(Calendar.YEAR);
        int birthMonth = birthCal.get(Calendar.MONTH) + 1; // Calendar中月份从0开始
        int birthDay = birthCal.get(Calendar.DAY_OF_MONTH);
        
        int age = year - birthYear;
        System.out.println(birthYear+"年"+birthMonth+"月"+birthDay+"号");
        if(birthMonth > month || (birthMonth == month && birthDay > day)){
            System.out.println("未过生日");
            age--;
        }
        return age;
    }

    @Override
    public CommonResult login(String username, String password) {
        User user = userMapper.login(username, password);
        if (user != null) {
            // 检查审核状态
            Integer auditStatus = user.getAudit_status();
            if (auditStatus == null || auditStatus == 0) {
                return new CommonResult(102, "您的账号正在审核中，请耐心等待", null);
            } else if (auditStatus == 2) {
                String remark = user.getAudit_remark();
                return new CommonResult(103, remark != null ? remark : "注册申请未通过审核", null);
            } else if (auditStatus == 1) {
                try {
                    // 生成token
                    String token = JWTUtil.buildToken(user.getId().toString(), user.getPassword());
                    user.setToken(token);
                    user.setPassword(null);  // 清除密码
                    Map<String, Object> result = new HashMap<>();
                    result.put("user", user);
                    result.put("token", token);
                    return new CommonResult(200, "登录成功", result);
                } catch (Exception e) {
                    return new CommonResult(500, "登录失败：" + e.getMessage(), null);
                }
            }
        }
        return new CommonResult(101, "用户名或密码错误", null);
    }

    @Override
    public CommonResult insert(User user) {
        CommonResult result = new CommonResult();
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username", user.getUsername());
        User exist1 = userMapper.selectOne(wrapper1);

        QueryWrapper<User> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("telephone", user.getTelephone());
        User exist2 = userMapper.selectOne(wrapper2);

        if (exist1 != null) {
            result.usernameExist(); //104
        } else if (exist2 != null) {
            result.phoneExist(); //105
        } else {
            user.setId(null);
            int i = userMapper.insert(user);
            if (i <= 0) {
                result.setNotInserted(); //101
            } else {
                result.setOK(user);
            }
        }
        return result;
    }

    @Override
    public CommonResult update(User user) {
        int i = userMapper.updateById(user);
        CommonResult result = new CommonResult(user.getBirthday());
        if (i <= 0) {
            result.setNotUpdate();
        }
        System.out.println(result);
        return result;
    }

    @Override
    public CommonResult selectByUsername(String username) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        List<User> list=baseMapper.selectList(queryWrapper);
        CommonResult result=new CommonResult(list);
        if (list==null||list.size()==0){
            result.setNotFound();
        }
        return result;
    }

    @Override
    public CommonResult selectByRid(int rid) {
        List<User> list=userMapper.selectByRid(rid);
        CommonResult result=new CommonResult(list);
        return result;
    }

    @Override
    public CommonResult selectByRidByPage(int rid, int current, int size) {
        int start=(current-1)*size;
        List<User> list=userMapper.selectByRidByPage(rid,start,size);
        List<User> getTotal=userMapper.selectByRid(rid);
        int total=getTotal.size();
        CommonResult result=new CommonResult(String.valueOf(total),list);
        if(list==null||list.size()==0){
            result.setNotFound();
        }
        return result;
    }

    @Override
    public CommonResult selectById(int id) {
        User user=userMapper.selectById(id);
        CommonResult result=new CommonResult(user);
        return result;
    }

    @Override
    public CommonResult selectByNameOrIdNum(String searchName) {
        String idNumFormat="^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9]|1[0-2]))(([0-2][1-9]|10|20|30|31))\\d{3}[0-9Xx]$";
        //身份证号查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (searchName.matches(idNumFormat)) {
            wrapper.eq("idNum", searchName);
            List<User> user = userMapper.selectList(wrapper);
            CommonResult result = new CommonResult(user);
            if (user==null){
                result.setNotFound();
            }
            System.out.println(result);
            return result;
        }
        //姓名查找
        else {
            wrapper.eq("name", searchName);
            List<User> user = userMapper.selectList(wrapper);
            CommonResult result = new CommonResult(user);
            if (user.size()==0||user==null){
                result.setNotFound();
            }
            return result;
        }
    }

    @Override
    public CommonResult getSum(int rId) {
        List<User> list=userMapper.selectByRid(rId);
        CommonResult result=new CommonResult(list.size());
        return result;
    }

    @Override
    public CommonResult getUsersSum() {
        List<User> list=userMapper.selectByRid(4);
        CommonResult result=new CommonResult(list.size());
        return result;
    }

    @Override
    public CommonResult getDoctorSum() {
        List<User> list=userMapper.selectByRid(3);
        CommonResult result=new CommonResult(list.size());
        return result;
    }

    @Override
    public CommonResult getWorkerSum() {
        List<User> list=userMapper.selectByRid(2);
        CommonResult result=new CommonResult(list.size());
        return result;
    }

    @Override
    public CommonResult getPendingAuditUsers() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("audit_status", 0);  // 查询待审核用户
        List<User> users = baseMapper.selectList(wrapper);
        return new CommonResult(200, "获取待审核用户列表成功", users);
    }
    
    @Override
    public CommonResult auditUser(Integer userId, Integer auditStatus, String auditRemark) {
        if(userId == null || auditStatus == null) {
            return new CommonResult(101, "参数错误", null);
        }
        
        User user = baseMapper.selectById(userId);
        if(user == null) {
            return new CommonResult(102, "用户不存在", null);
        }
        
        user.setAuditStatus(auditStatus);
        user.setAuditRemark(auditRemark);
        
        int result = baseMapper.updateById(user);
        if(result > 0) {
            return new CommonResult(200, "审核操作成功", null);
        }
        return new CommonResult(103, "审核操作失败", null);
    }

    @Override
    public CommonResult getPendingUsers(int current, int size) {
        try {
            int start = (current - 1) * size;
            List<User> pendingUsers = userMapper.selectPendingUsers(start, size);
            int total = userMapper.countPendingUsers();
            
            if (pendingUsers != null && !pendingUsers.isEmpty()) {
                Map<String, Object> data = new HashMap<>();
                data.put("records", pendingUsers);
                data.put("total", total);
                return new CommonResult(200, "获取待审核用户列表成功", data);
            } else {
                return new CommonResult(404, "暂无待审核用户", null);
            }
        } catch (Exception e) {
            return new CommonResult(500, "获取待审核用户列表失败：" + e.getMessage(), null);
        }
    }

    @Override
    public CommonResult approveUser(Integer id) {
        try {
            User user = userMapper.selectById(id);
            if (user == null) {
                return new CommonResult(404, "用户不存在", null);
            }
            
            user.setAuditStatus(1);
            user.setAuditRemark("审核通过");
            
            if (userMapper.updateById(user) > 0) {
                return new CommonResult(200, "审核通过成功", null);
            } else {
                return new CommonResult(500, "审核通过失败", null);
            }
        } catch (Exception e) {
            return new CommonResult(500, "审核通过失败：" + e.getMessage(), null);
        }
    }

    @Override
    public CommonResult rejectUser(Integer id) {
        try {
            User user = userMapper.selectById(id);
            if (user == null) {
                return new CommonResult(404, "用户不存在", null);
            }
            
            user.setAuditStatus(2);
            user.setAuditRemark("审核不通过");
            
            if (userMapper.updateById(user) > 0) {
                return new CommonResult(200, "审核拒绝成功", null);
            } else {
                return new CommonResult(500, "审核拒绝失败", null);
            }
        } catch (Exception e) {
            return new CommonResult(500, "审核拒绝失败：" + e.getMessage(), null);
        }
    }
}

